/*
 * @Description: 全宗reducer
 * @Author: Rfan
 * @Date: 2022-04-06 13:13:27
 * @LastEditTime: 2022-04-22 14:25:46
 */

import { arrToTree } from '@/utils';
import { delItemByIdArray, editItemById } from '@/utils/list';
import {
  ADD_TREE_DATA,
  DELETE_TREE_DATA,
  EDIT_TREE_DATA,
  SAVE_REF,
  SET_SELECT_NAV,
  SET_TREE_DATA
} from '../constants';
import { SET_SELECTED_ITEM } from '@/view/sysMaintenance/FlowMgt/constants';

export const FuncAndNavReducer = (state, action) => {
  switch (action.type) {
    /**
     * @description: 保存表格选中的条目id
     * @param {number[]} data
     */
    case SET_SELECTED_ITEM:
      return { ...state, selectItems: action.data };

    /**
     * @description: 设置导航树结构
     */
    case SET_TREE_DATA:
      return {
        ...state,
        flatData: action.data,
        treeData: arrToTree(action.data)
      };

    /**
     * @description: 增加导航树节点
     */
    case ADD_TREE_DATA: {
      const flatData = [...state.flatData, action.data];
      return {
        ...state,
        flatData,
        treeData: arrToTree(flatData)
      };
    }

    /**
     * @description: 编辑导航树节点
     */
    case EDIT_TREE_DATA: {
      const flatData = editItemById(action.id, action.data, state.flatData);
      return {
        ...state,
        flatData,
        treeData: arrToTree(flatData)
      };
    }

    /**
     * @description: 设置表单ref
     */
    case SAVE_REF: {
      return {
        ...state,
        formRef: action.data
      };
    }

    /**
     * @description: 删除导航树节点
     */
    case DELETE_TREE_DATA: {
      const flatData = delItemByIdArray(action.ids, state.flatData);
      return {
        ...state,
        flatData,
        treeData: arrToTree(flatData)
      };
    }

    /**
     * @description: 设置选中的导航信息
     */
    case SET_SELECT_NAV: {
      return {
        ...state,
        selectNav: action.data
      };
    }

    default:
      console.log('untouched', action);
      return state;
  }
};
